#!/bin/bash
# 用法: 
#   ./napcat.sh start 123456          # 启动指定QQ号的容器
#   ./napcat.sh stop 123456           # 停止指定QQ号的容器
#   ./napcat.sh restart 123456        # 重启指定QQ号的容器
#   ./napcat.sh rm 123456             # 删除指定QQ号的容器和配置
#   ./napcat.sh logs [options] 123456 # 查看指定QQ号容器的日志（默认显示所有日志）
#   ./napcat.sh ls                    # 列出所有napcat容器

set -u

# -----------------------------
# 获取脚本真实路径
# -----------------------------
# 获取脚本的真实路径，支持软链接
SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"

# 切换到脚本所在目录，确保相对路径正确
cd "$SCRIPT_DIR" || {
  echo "❌ 无法切换到脚本目录: $SCRIPT_DIR"
  exit 1
}

# -----------------------------
# Docker权限检测和sudo处理
# -----------------------------
DOCKER_CMD="docker"
DOCKER_COMPOSE_CMD="docker compose"

# 检测是否需要sudo执行docker
check_docker_permission() {
  if docker ps >/dev/null 2>&1; then
    # 直接可以执行docker，无需sudo
    return 0
  elif sudo docker ps >/dev/null 2>&1; then
    # 需要sudo执行docker
    DOCKER_CMD="sudo docker"
    DOCKER_COMPOSE_CMD="sudo docker compose"
    echo "🔐 检测到需要sudo权限执行Docker命令"
    return 0
  else
    echo "❌ Docker未安装或权限配置有问题"
    echo "💡 请确保:"
    echo "   1. Docker已正确安装"
    echo "   2. 当前用户已加入docker组: sudo usermod -aG docker \$USER"
    echo "   3. 重新登录系统使组权限生效"
    echo "   4. 或者使用sudo运行此脚本"
    exit 1
  fi
}

# 初始化时检查Docker权限
check_docker_permission

# 列出所有napcat容器的函数
list_containers() {
  echo "📋 当前napcat容器列表:"
  echo "----------------------------------------"
  
  # 获取所有napcat容器
  container_names=$($DOCKER_CMD ps -a --filter "name=napcat_" --format "{{.Names}}" 2>/dev/null)
  
  if [ -z "$container_names" ]; then
    echo "🔍 未找到任何napcat容器"
    return
  fi
  
  # 显示表头
  printf "%-12s %-20s %-30s\n" "QQ号" "状态" "端口映射"
  echo "----------------------------------------"
  
  # 遍历每个容器获取详细信息
  echo "$container_names" | while read container_name; do
    # 从容器名提取QQ号 (napcat_123456 -> 123456)
    qq_number=$(echo "$container_name" | sed 's/napcat_//')
    
    # 获取容器状态
    status=$($DOCKER_CMD inspect --format '{{.State.Status}}' "$container_name" 2>/dev/null)
    
    # 获取端口映射信息（即使容器停止也能获取）
    ports=$($DOCKER_CMD inspect --format '{{range .HostConfig.PortBindings}}{{range .}}{{.HostPort}}{{end}} {{end}}' "$container_name" 2>/dev/null | tr ' ' '\n' | grep -v '^$' | sort -n | tr '\n' ',' | sed 's/,$//')
    
    # 如果没有获取到端口，尝试从运行时获取
    if [ -z "$ports" ]; then
      ports=$($DOCKER_CMD port "$container_name" 2>/dev/null | cut -d':' -f2 | tr '\n' ',' | sed 's/,$//')
    fi
    
    # 格式化状态显示
    case "$status" in
      "running")
        status_display="运行中"
        ;;
      "exited")
        status_display="已停止"
        ;;
      "paused")
        status_display="已暂停"
        ;;
      "restarting")
        status_display="重启中"
        ;;
      *)
        status_display="❓ $status"
        ;;
    esac
    
    # 显示信息
    printf "%-12s %-20s %-30s\n" "$qq_number" "$status_display" "$ports"
  done
  
  echo "----------------------------------------"
  
  # 统计容器数量
  running_count=$($DOCKER_CMD ps --filter "name=napcat_" --filter "status=running" --quiet | wc -l)
  total_count=$($DOCKER_CMD ps -a --filter "name=napcat_" --quiet | wc -l)
  
  echo "📊 统计: 运行中 $running_count/$total_count 个容器"
}

# 停止容器的函数
stop_container() {
  local qq="$1"
  local container_name="napcat_$qq"
  
  echo "🛑 正在停止容器: $container_name"
  
  if ! $DOCKER_CMD ps --filter "name=$container_name" --quiet | grep -q .; then
    echo "⚠️ 容器 $container_name 未在运行"
    return 1
  fi
  
  if $DOCKER_CMD stop "$container_name" >/dev/null 2>&1; then
    echo "✅ 已停止容器: $container_name"
  else
    echo "❌ 停止容器失败: $container_name"
    return 1
  fi
}

# 重启容器的函数
restart_container() {
  local qq="$1"
  local container_name="napcat_$qq"
  
  echo "🔄 正在重启容器: $container_name"
  
  # 检查容器是否存在
  if ! $DOCKER_CMD ps -a --filter "name=$container_name" --quiet | grep -q .; then
    echo "❌ 容器 $container_name 不存在，无法重启"
    return 1
  fi
  
  # 重启容器
  if $DOCKER_CMD restart "$container_name" >/dev/null 2>&1; then
    echo "✅ 已重启容器: $container_name"
    echo "📡 开始实时跟踪日志（Ctrl+C 退出日志跟踪，不影响容器运行）..."
    echo "----------------------------------------"
    
    # 等待容器完全启动
    sleep 2
    
    # 实时跟踪日志，使用trap捕获Ctrl+C信号
    trap 'echo -e "\n🔚 已退出日志跟踪，容器 '$container_name' 继续在后台运行"; exit 0' INT
    $DOCKER_CMD logs --tail 50 -f "$container_name"
  else
    echo "❌ 重启容器失败: $container_name"
    return 1
  fi
}

# 删除容器和配置的函数
remove_container() {
  local qq="$1"
  local container_name="napcat_$qq"
  local config_dir="./$qq"
  
  echo "🗑️ 正在删除容器和配置: $container_name"
  
  # 停止容器（如果正在运行）
  if docker ps --filter "name=$container_name" --quiet | grep -q .; then
    echo "🛑 先停止运行中的容器..."
    docker stop "$container_name" >/dev/null 2>&1
  fi
  
  # 删除容器
  if docker ps -a --filter "name=$container_name" --quiet | grep -q .; then
    if docker rm "$container_name" >/dev/null 2>&1; then
      echo "✅ 已删除容器: $container_name"
    else
      echo "❌ 删除容器失败: $container_name"
      return 1
    fi
  else
    echo "⚠️ 容器 $container_name 不存在"
  fi
  
  # 删除配置目录
  if [ -d "$config_dir" ]; then
    if rm -rf "$config_dir"; then
      echo "✅ 已删除配置目录: $config_dir"
    else
      echo "❌ 删除配置目录失败: $config_dir"
      return 1
    fi
  else
    echo "⚠️ 配置目录 $config_dir 不存在"
  fi
  
  echo "🎉 完成删除操作: QQ $qq"
}

# 查看容器日志的函数
show_logs() {
  local qq="$1"
  local follow="${2:-false}"
  local tail_lines="${3:-all}"
  local since="${4:-}"
  local until="${5:-}"
  local timestamps="${6:-false}"
  local details="${7:-false}"
  local container_name="napcat_$qq"
  
  echo "📋 查看容器日志: $container_name"
  
  # 检查容器是否存在
  if ! docker ps -a --filter "name=$container_name" --quiet | grep -q .; then
    echo "❌ 容器 $container_name 不存在"
    return 1
  fi
  
  echo "----------------------------------------"
  
  # 构建docker logs命令
  local docker_cmd="docker logs"
  
  # 添加tail参数
  if [ "$tail_lines" != "all" ]; then
    docker_cmd="$docker_cmd --tail $tail_lines"
  fi
  
  # 添加since参数
  if [ -n "$since" ]; then
    docker_cmd="$docker_cmd --since $since"
  fi
  
  # 添加until参数
  if [ -n "$until" ]; then
    docker_cmd="$docker_cmd --until $until"
  fi
  
  # 添加timestamps参数
  if [ "$timestamps" = "true" ]; then
    docker_cmd="$docker_cmd --timestamps"
  fi
  
  # 添加details参数
  if [ "$details" = "true" ]; then
    docker_cmd="$docker_cmd --details"
  fi
  
  # 添加follow参数
  if [ "$follow" = "true" ]; then
    docker_cmd="$docker_cmd --follow"
    echo "📡 实时跟踪日志（Ctrl+C 退出）..."
  else
    if [ "$tail_lines" = "all" ]; then
      echo "📄 显示所有日志:"
    else
      echo "📄 显示最近${tail_lines}行日志:"
    fi
  fi
  
  # 添加容器名称并执行命令
  docker_cmd="$docker_cmd $container_name"
  eval "$docker_cmd"
}

# 解析命令行参数
if [ $# -eq 0 ]; then
  echo "❌ 请提供参数"
  echo "用法: $0 {start|stop|restart|rm|logs|ls} [选项] [QQ号]"
  exit 1
fi

COMMAND="$1"
shift

# 处理logs命令的特殊参数解析
if [ "$COMMAND" = "logs" ]; then
  FOLLOW_MODE="false"
  TAIL_LINES="all"
  SINCE=""
  UNTIL=""
  TIMESTAMPS="false"
  DETAILS="false"
  QQ=""
  
  # 解析logs命令的参数
  while [ $# -gt 0 ]; do
    case "$1" in
      -f|--follow)
        FOLLOW_MODE="true"
        shift
        ;;
      -n|--tail)
        if [ $# -lt 2 ]; then
          echo "❌ 参数 $1 需要一个值"
          echo "用法: $0 logs [选项] QQ号"
          exit 1
        fi
        TAIL_LINES="$2"
        shift 2
        ;;
      --tail=*)
        TAIL_LINES="${1#*=}"
        shift
        ;;
      --since)
        if [ $# -lt 2 ]; then
          echo "❌ 参数 $1 需要一个值"
          echo "用法: $0 logs [选项] QQ号"
          exit 1
        fi
        SINCE="$2"
        shift 2
        ;;
      --since=*)
        SINCE="${1#*=}"
        shift
        ;;
      --until)
        if [ $# -lt 2 ]; then
          echo "❌ 参数 $1 需要一个值"
          echo "用法: $0 logs [选项] QQ号"
          exit 1
        fi
        UNTIL="$2"
        shift 2
        ;;
      --until=*)
        UNTIL="${1#*=}"
        shift
        ;;
      -t|--timestamps)
        TIMESTAMPS="true"
        shift
        ;;
      --details)
        DETAILS="true"
        shift
        ;;
      -*)
        echo "❌ 未知参数: $1"
        echo "用法: $0 logs [选项] QQ号"
        echo "选项:"
        echo "  -f, --follow        实时跟踪日志输出"
        echo "  -n, --tail LINES    显示末尾指定行数的日志 (默认: all)"
        echo "  --since TIMESTAMP   显示指定时间戳之后的日志"
        echo "  --until TIMESTAMP   显示指定时间戳之前的日志"
        echo "  -t, --timestamps    显示时间戳"
        echo "  --details           显示额外的详细信息"
        exit 1
        ;;
      *)
        if [ -z "$QQ" ]; then
          QQ="$1"
          shift
        else
          echo "❌ 未知参数: $1"
          echo "用法: $0 logs [选项] QQ号"
          exit 1
        fi
        ;;
    esac
  done
  
  if [ -z "$QQ" ]; then
    echo "❌ 请提供QQ号"
    echo "用法: $0 logs [选项] QQ号"
    exit 1
  fi
  
  show_logs "$QQ" "$FOLLOW_MODE" "$TAIL_LINES" "$SINCE" "$UNTIL" "$TIMESTAMPS" "$DETAILS"
  exit $?
fi

case "$COMMAND" in
  ls)
    list_containers
    exit 0
    ;;
  start|stop|restart|rm)
    if [ $# -eq 0 ]; then
      echo "❌ 请提供QQ号"
      echo "用法: $0 $COMMAND QQ号"
      exit 1
    fi
    QQ="$1"
    if [ -z "$QQ" ]; then
      echo "❌ QQ号不能为空"
      exit 1
    fi
    ;;
  *)
    echo "❌ 未知命令: $COMMAND"
    echo "用法: $0 {start|stop|restart|rm|logs|ls} [选项] [QQ号]"
    exit 1
    ;;
esac

# 执行相应的操作
case "$COMMAND" in
  start)
    # 检查容器是否已经在运行
    container_name="napcat_$QQ"
    if docker ps --filter "name=$container_name" --quiet | grep -q .; then
      echo "⚠️ 容器 $container_name 已经在运行中"
      echo "💡 如需重启，请使用: $0 restart $QQ"
      echo "📋 如需查看日志，请使用: $0 logs $QQ"
      exit 0
    fi
    
    # 检查容器是否存在但未运行
    if docker ps -a --filter "name=$container_name" --quiet | grep -q .; then
      echo "🔄 发现已存在的容器 $container_name（未运行），正在启动..."
      if docker start "$container_name" >/dev/null 2>&1; then
        echo "✅ 已启动容器: $container_name"
        echo "📡 开始实时跟踪日志（Ctrl+C 退出日志跟踪，不影响容器运行）..."
        echo "----------------------------------------"
        
        # 等待容器完全启动
        sleep 2
        
        # 实时跟踪日志，使用trap捕获Ctrl+C信号
        trap 'echo -e "\n🔚 已退出日志跟踪，容器 '$container_name' 继续在后台运行"; exit 0' INT
        docker logs --tail 50 -f "$container_name"
      else
        echo "❌ 启动容器失败: $container_name"
        exit 1
      fi
      exit 0
    fi
    
    # 原有的启动逻辑继续执行
    ;;
  stop)
    stop_container "$QQ"
    exit $?
    ;;
  restart)
    restart_container "$QQ"
    exit $?
    ;;
  rm)
    remove_container "$QQ"
    exit $?
    ;;
esac


# -----------------------------
# 端口检测工具函数（三重兜底）
# -----------------------------
is_port_listened() {
  local port="$1"
  # 优先 ss
  if command -v ss >/dev/null 2>&1; then
    # 仅抓取本机监听 TCP 端口
    if ss -H -ltn 2>/dev/null | awk '{print $4}' | sed -E 's/.*:([0-9]+)$/\1/' | grep -qx "$port"; then
      return 0
    fi
  fi
  # 其次 lsof
  if command -v lsof >/dev/null 2>&1; then
    if lsof -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1; then
      return 0
    fi
  fi
  # 最后 netstat
  if command -v netstat >/dev/null 2>&1; then
    if netstat -ltn 2>/dev/null | awk '{print $4}' | sed -E 's/.*:([0-9]+)$/\1/' | grep -qx "$port"; then
      return 0
    fi
  fi
  return 1
}

# 收集 Docker 已发布的主机端口（运行、停止、暂停的容器）
get_docker_published_ports() {
  # 收集所有 napcat 容器（包括 stopped）占用的端口
  docker ps -a --filter "name=napcat_" --format '{{.Names}}' 2>/dev/null | while read cname; do
    # 方法1: 从容器配置中获取端口映射（适用于所有状态的容器）
    docker inspect --format='{{range $p, $conf := .Config.ExposedPorts}}{{$p}}{{"\n"}}{{end}}' "$cname" 2>/dev/null | sed 's|/tcp||g' | sed 's|/udp||g'
    
    # 方法2: 从网络设置中获取端口映射（主要适用于运行中的容器，但也尝试停止的容器）
    docker inspect --format='{{range .NetworkSettings.Ports}}{{if .}}{{range .}}{{.HostPort}}{{"\n"}}{{end}}{{end}}{{end}}' "$cname" 2>/dev/null
    
    # 方法3: 从HostConfig中获取端口绑定（适用于所有状态的容器）
    docker inspect --format='{{range .HostConfig.PortBindings}}{{range .}}{{.HostPort}}{{"\n"}}{{end}}{{end}}' "$cname" 2>/dev/null
  done | grep -E '^[0-9]+$' | sort -n | uniq
}

# 查找 >=START 的第一个"未被进程监听且未被任何Docker容器占用"的端口
find_first_available_port() {
  local START="${1:-6099}"
  local MAX_TRY="${2:-20000}"  # 最多尝试这么多递增
  mapfile -t DOCKER_PORTS < <(get_docker_published_ports)

  for ((i=0; i<MAX_TRY; i++)); do
    local port=$((START + i))

    # 1) 不在 docker 已发布端口里（包括运行中和已停止的容器）
    local used_by_docker=0
    for dp in "${DOCKER_PORTS[@]:-}"; do
      if [ "$dp" = "$port" ]; then
        used_by_docker=1
        break
      fi
    done
    if [ $used_by_docker -eq 1 ]; then
      continue
    fi

    # 2) 无进程监听
    if ! is_port_listened "$port"; then
      echo "$port"
      return 0
    fi
  done
  
  echo "❌ 未找到可用端口（从 $START 起向上搜索）。"
  return 1
}

# 创建独立目录
mkdir -p "./$QQ/napcat" "./$QQ/ntqq"

# 显示当前已占用的端口信息
echo "🔍 检查端口占用情况..."
OCCUPIED_PORTS=$(get_docker_published_ports | tr '\n' ' ')
if [ -n "$OCCUPIED_PORTS" ]; then
  echo "📋 已占用的Docker端口: $OCCUPIED_PORTS"
else
  echo "📋 未发现已占用的Docker端口"
fi

WEBUI_PORT=$(find_first_available_port 6099 50000)
if [ -z "${WEBUI_PORT:-}" ]; then
  echo "❌ 未找到可用端口（从 6099 起向上搜索）。"
  exit 1
fi
echo "🔎 选择WebUI端口: $WEBUI_PORT → 容器 $WEBUI_PORT"

HTTP_PORT=$(find_first_available_port 3000 50000)
if [ -z "${HTTP_PORT:-}" ]; then
  echo "❌ 未找到可用端口（从 3000 起向上搜索）。"
  exit 1
fi
echo "🔎 选择HTTP端口: $HTTP_PORT → 容器 $HTTP_PORT"

# 如果配置不存在则生成（避免覆盖已有配置）
CONFIG_FILE="./$QQ/napcat/onebot11_$QQ.json"
if [ ! -f "$CONFIG_FILE" ]; then
cat > "$CONFIG_FILE" <<EOF
{
  "network": {
    "httpServers": [
      {
        "enable": true,
        "name": "http",
        "host": "0.0.0.0",
        "port": $HTTP_PORT,
        "enableCors": true,
        "enableWebsocket": true,
        "messagePostFormat": "array",
        "token": "",
        "debug": true
      }
    ],
    "httpSseServers": [],
    "httpClients": [],
    "websocketServers": [],
    "websocketClients": [
      {
        "enable": true,
        "name": "eva",
        "url": "wss://eva.woolsen.cn/ws/onebot",
        "reportSelfMessage": false,
        "messagePostFormat": "array",
        "token": "",
        "debug": true,
        "heartInterval": 30000,
        "reconnectInterval": 30000
      }
    ],
    "plugins": []
  },
  "musicSignUrl": "",
  "enableLocalFile2Url": false,
  "parseMultMsg": false
}
EOF
  echo "✅ 已生成配置文件: $CONFIG_FILE"
else
  echo "⚠️ 已存在配置文件: $CONFIG_FILE"
fi

# 如果配置不存在则生成（避免覆盖已有配置）
CONFIG_FILE2="./$QQ/napcat/napcat_$QQ.json"
if [ ! -f "$CONFIG_FILE2" ]; then
cat > "$CONFIG_FILE2" <<'EOF'
{
  "fileLog": true,
  "consoleLog": true,
  "fileLogLevel": "debug",
  "consoleLogLevel": "info",
  "packetBackend": "auto",
  "packetServer": "",
  "o3HookMode": 1
}
EOF
  echo "✅ 已生成配置文件: $CONFIG_FILE2"
else
  echo "⚠️ 已存在配置文件: $CONFIG_FILE2"
fi

# 如果配置不存在则生成（避免覆盖已有配置）
CONFIG_FILE3="./$QQ/napcat/webui.json"
if [ ! -f "$CONFIG_FILE3" ]; then
cat > "$CONFIG_FILE3" <<EOF
{
    "host": "0.0.0.0",
    "port": $WEBUI_PORT,
    "token": "123456",
    "loginRate": 10,
    "autoLoginAccount": "$QQ",
    "theme": {
        "dark": {
            "--heroui-background": "0 0% 0%",
            "--heroui-foreground-50": "240 5.88% 10%",
            "--heroui-foreground-100": "240 3.7% 15.88%",
            "--heroui-foreground-200": "240 5.26% 26.08%",
            "--heroui-foreground-300": "240 5.2% 33.92%",
            "--heroui-foreground-400": "240 3.83% 46.08%",
            "--heroui-foreground-500": "240 5.03% 64.9%",
            "--heroui-foreground-600": "240 4.88% 83.92%",
            "--heroui-foreground-700": "240 5.88% 90%",
            "--heroui-foreground-800": "240 4.76% 95.88%",
            "--heroui-foreground-900": "0 0% 98.04%",
            "--heroui-foreground": "210 5.56% 92.94%",
            "--heroui-focus": "212.01999999999998 100% 46.67%",
            "--heroui-overlay": "0 0% 0%",
            "--heroui-divider": "0 0% 100%",
            "--heroui-divider-opacity": "0.15",
            "--heroui-content1": "240 5.88% 10%",
            "--heroui-content1-foreground": "0 0% 98.04%",
            "--heroui-content2": "240 3.7% 15.88%",
            "--heroui-content2-foreground": "240 4.76% 95.88%",
            "--heroui-content3": "240 5.26% 26.08%",
            "--heroui-content3-foreground": "240 5.88% 90%",
            "--heroui-content4": "240 5.2% 33.92%",
            "--heroui-content4-foreground": "240 4.88% 83.92%",
            "--heroui-default-50": "240 5.88% 10%",
            "--heroui-default-100": "240 3.7% 15.88%",
            "--heroui-default-200": "240 5.26% 26.08%",
            "--heroui-default-300": "240 5.2% 33.92%",
            "--heroui-default-400": "240 3.83% 46.08%",
            "--heroui-default-500": "240 5.03% 64.9%",
            "--heroui-default-600": "240 4.88% 83.92%",
            "--heroui-default-700": "240 5.88% 90%",
            "--heroui-default-800": "240 4.76% 95.88%",
            "--heroui-default-900": "0 0% 98.04%",
            "--heroui-default-foreground": "0 0% 100%",
            "--heroui-default": "240 5.26% 26.08%",
            "--heroui-danger-50": "301.89 82.61% 22.55%",
            "--heroui-danger-100": "308.18 76.39% 28.24%",
            "--heroui-danger-200": "313.85 70.65% 36.08%",
            "--heroui-danger-300": "319.73 65.64% 44.51%",
            "--heroui-danger-400": "325.82 69.62% 53.53%",
            "--heroui-danger-500": "331.82 75% 65.49%",
            "--heroui-danger-600": "337.84 83.46% 73.92%",
            "--heroui-danger-700": "343.42 90.48% 83.53%",
            "--heroui-danger-800": "350.53 90.48% 91.76%",
            "--heroui-danger-900": "324 90.91% 95.69%",
            "--heroui-danger-foreground": "0 0% 100%",
            "--heroui-danger": "325.82 69.62% 53.53%",
            "--heroui-primary-50": "340 84.91% 10.39%",
            "--heroui-primary-100": "339.33 86.54% 20.39%",
            "--heroui-primary-200": "339.11 85.99% 30.78%",
            "--heroui-primary-300": "339 86.54% 40.78%",
            "--heroui-primary-400": "339.2 90.36% 51.18%",
            "--heroui-primary-500": "339 90% 60.78%",
            "--heroui-primary-600": "339.11 90.6% 70.78%",
            "--heroui-primary-700": "339.33 90% 80.39%",
            "--heroui-primary-800": "340 91.84% 90.39%",
            "--heroui-primary-900": "339.13 92% 95.1%",
            "--heroui-primary-foreground": "0 0% 100%",
            "--heroui-primary": "339.2 90.36% 51.18%",
            "--heroui-secondary-50": "270 66.67% 9.41%",
            "--heroui-secondary-100": "270 66.67% 18.82%",
            "--heroui-secondary-200": "270 66.67% 28.24%",
            "--heroui-secondary-300": "270 66.67% 37.65%",
            "--heroui-secondary-400": "270 66.67% 47.06%",
            "--heroui-secondary-500": "270 59.26% 57.65%",
            "--heroui-secondary-600": "270 59.26% 68.24%",
            "--heroui-secondary-700": "270 59.26% 78.82%",
            "--heroui-secondary-800": "270 59.26% 89.41%",
            "--heroui-secondary-900": "270 61.54% 94.9%",
            "--heroui-secondary-foreground": "0 0% 100%",
            "--heroui-secondary": "270 59.26% 57.65%",
            "--heroui-success-50": "145.71 77.78% 8.82%",
            "--heroui-success-100": "146.2 79.78% 17.45%",
            "--heroui-success-200": "145.79 79.26% 26.47%",
            "--heroui-success-300": "146.01 79.89% 35.1%",
            "--heroui-success-400": "145.96 79.46% 43.92%",
            "--heroui-success-500": "146.01 62.45% 55.1%",
            "--heroui-success-600": "145.79 62.57% 66.47%",
            "--heroui-success-700": "146.2 61.74% 77.45%",
            "--heroui-success-800": "145.71 61.4% 88.82%",
            "--heroui-success-900": "146.67 64.29% 94.51%",
            "--heroui-success-foreground": "0 0% 0%",
            "--heroui-success": "145.96 79.46% 43.92%",
            "--heroui-warning-50": "37.14 75% 10.98%",
            "--heroui-warning-100": "37.14 75% 21.96%",
            "--heroui-warning-200": "36.96 73.96% 33.14%",
            "--heroui-warning-300": "37.01 74.22% 44.12%",
            "--heroui-warning-400": "37.03 91.27% 55.1%",
            "--heroui-warning-500": "37.01 91.26% 64.12%",
            "--heroui-warning-600": "36.96 91.24% 73.14%",
            "--heroui-warning-700": "37.14 91.3% 81.96%",
            "--heroui-warning-800": "37.14 91.3% 90.98%",
            "--heroui-warning-900": "54.55 91.67% 95.29%",
            "--heroui-warning-foreground": "0 0% 0%",
            "--heroui-warning": "37.03 91.27% 55.1%",
            "--heroui-code-background": "240 5.56% 7.06%",
            "--heroui-strong": "190.14 94.67% 44.12%",
            "--heroui-code-mdx": "190.14 94.67% 44.12%",
            "--heroui-divider-weight": "1px",
            "--heroui-disabled-opacity": ".5",
            "--heroui-font-size-tiny": "0.75rem",
            "--heroui-font-size-small": "0.875rem",
            "--heroui-font-size-medium": "1rem",
            "--heroui-font-size-large": "1.125rem",
            "--heroui-line-height-tiny": "1rem",
            "--heroui-line-height-small": "1.25rem",
            "--heroui-line-height-medium": "1.5rem",
            "--heroui-line-height-large": "1.75rem",
            "--heroui-radius-small": "8px",
            "--heroui-radius-medium": "12px",
            "--heroui-radius-large": "14px",
            "--heroui-border-width-small": "1px",
            "--heroui-border-width-medium": "2px",
            "--heroui-border-width-large": "3px",
            "--heroui-box-shadow-small": "0px 0px 5px 0px rgba(0, 0, 0, .05), 0px 2px 10px 0px rgba(0, 0, 0, .2), inset 0px 0px 1px 0px hsla(0, 0%, 100%, .15)",
            "--heroui-box-shadow-medium": "0px 0px 15px 0px rgba(0, 0, 0, .06), 0px 2px 30px 0px rgba(0, 0, 0, .22), inset 0px 0px 1px 0px hsla(0, 0%, 100%, .15)",
            "--heroui-box-shadow-large": "0px 0px 30px 0px rgba(0, 0, 0, .07), 0px 30px 60px 0px rgba(0, 0, 0, .26), inset 0px 0px 1px 0px hsla(0, 0%, 100%, .15)",
            "--heroui-hover-opacity": ".9"
        },
        "light": {
            "--heroui-background": "0 0% 100%",
            "--heroui-foreground-50": "240 5.88% 95%",
            "--heroui-foreground-100": "240 3.7% 90%",
            "--heroui-foreground-200": "240 5.26% 80%",
            "--heroui-foreground-300": "240 5.2% 70%",
            "--heroui-foreground-400": "240 3.83% 60%",
            "--heroui-foreground-500": "240 5.03% 50%",
            "--heroui-foreground-600": "240 4.88% 40%",
            "--heroui-foreground-700": "240 5.88% 30%",
            "--heroui-foreground-800": "240 4.76% 20%",
            "--heroui-foreground-900": "0 0% 10%",
            "--heroui-foreground": "210 5.56% 7.06%",
            "--heroui-focus": "212.01999999999998 100% 53.33%",
            "--heroui-overlay": "0 0% 100%",
            "--heroui-divider": "0 0% 0%",
            "--heroui-divider-opacity": "0.85",
            "--heroui-content1": "240 5.88% 95%",
            "--heroui-content1-foreground": "0 0% 10%",
            "--heroui-content2": "240 3.7% 90%",
            "--heroui-content2-foreground": "240 4.76% 20%",
            "--heroui-content3": "240 5.26% 80%",
            "--heroui-content3-foreground": "240 5.88% 30%",
            "--heroui-content4": "240 5.2% 70%",
            "--heroui-content4-foreground": "240 4.88% 40%",
            "--heroui-default-50": "240 5.88% 95%",
            "--heroui-default-100": "240 3.7% 90%",
            "--heroui-default-200": "240 5.26% 80%",
            "--heroui-default-300": "240 5.2% 70%",
            "--heroui-default-400": "240 3.83% 60%",
            "--heroui-default-500": "240 5.03% 50%",
            "--heroui-default-600": "240 4.88% 40%",
            "--heroui-default-700": "240 5.88% 30%",
            "--heroui-default-800": "240 4.76% 20%",
            "--heroui-default-900": "0 0% 10%",
            "--heroui-default-foreground": "0 0% 0%",
            "--heroui-default": "240 5.26% 80%",
            "--heroui-danger-50": "324 90.91% 95.69%",
            "--heroui-danger-100": "350.53 90.48% 91.76%",
            "--heroui-danger-200": "343.42 90.48% 83.53%",
            "--heroui-danger-300": "337.84 83.46% 73.92%",
            "--heroui-danger-400": "331.82 75% 65.49%",
            "--heroui-danger-500": "325.82 69.62% 53.53%",
            "--heroui-danger-600": "319.73 65.64% 44.51%",
            "--heroui-danger-700": "313.85 70.65% 36.08%",
            "--heroui-danger-800": "308.18 76.39% 28.24%",
            "--heroui-danger-900": "301.89 82.61% 22.55%",
            "--heroui-danger-foreground": "0 0% 100%",
            "--heroui-danger": "325.82 69.62% 53.53%",
            "--heroui-primary-50": "339.13 92% 95.1%",
            "--heroui-primary-100": "340 91.84% 90.39%",
            "--heroui-primary-200": "339.33 90% 80.39%",
            "--heroui-primary-300": "339.11 90.6% 70.78%",
            "--heroui-primary-400": "339 90% 60.78%",
            "--heroui-primary-500": "339.2 90.36% 51.18%",
            "--heroui-primary-600": "339 86.54% 40.78%",
            "--heroui-primary-700": "339.11 85.99% 30.78%",
            "--heroui-primary-800": "339.33 86.54% 20.39%",
            "--heroui-primary-900": "340 84.91% 10.39%",
            "--heroui-primary-foreground": "0 0% 100%",
            "--heroui-primary": "339.2 90.36% 51.18%",
            "--heroui-secondary-50": "270 61.54% 94.9%",
            "--heroui-secondary-100": "270 59.26% 89.41%",
            "--heroui-secondary-200": "270 59.26% 78.82%",
            "--heroui-secondary-300": "270 59.26% 68.24%",
            "--heroui-secondary-400": "270 59.26% 57.65%",
            "--heroui-secondary-500": "270 66.67% 47.06%",
            "--heroui-secondary-600": "270 66.67% 37.65%",
            "--heroui-secondary-700": "270 66.67% 28.24%",
            "--heroui-secondary-800": "270 66.67% 18.82%",
            "--heroui-secondary-900": "270 66.67% 9.41%",
            "--heroui-secondary-foreground": "0 0% 100%",
            "--heroui-secondary": "270 66.67% 47.06%",
            "--heroui-success-50": "146.67 64.29% 94.51%",
            "--heroui-success-100": "145.71 61.4% 88.82%",
            "--heroui-success-200": "146.2 61.74% 77.45%",
            "--heroui-success-300": "145.79 62.57% 66.47%",
            "--heroui-success-400": "146.01 62.45% 55.1%",
            "--heroui-success-500": "145.96 79.46% 43.92%",
            "--heroui-success-600": "146.01 79.89% 35.1%",
            "--heroui-success-700": "145.79 79.26% 26.47%",
            "--heroui-success-800": "146.2 79.78% 17.45%",
            "--heroui-success-900": "145.71 77.78% 8.82%",
            "--heroui-success-foreground": "0 0% 0%",
            "--heroui-success": "145.96 79.46% 43.92%",
            "--heroui-warning-50": "54.55 91.67% 95.29%",
            "--heroui-warning-100": "37.14 91.3% 90.98%",
            "--heroui-warning-200": "37.14 91.3% 81.96%",
            "--heroui-warning-300": "36.96 91.24% 73.14%",
            "--heroui-warning-400": "37.01 91.26% 64.12%",
            "--heroui-warning-500": "37.03 91.27% 55.1%",
            "--heroui-warning-600": "37.01 74.22% 44.12%",
            "--heroui-warning-700": "36.96 73.96% 33.14%",
            "--heroui-warning-800": "37.14 75% 21.96%",
            "--heroui-warning-900": "37.14 75% 10.98%",
            "--heroui-warning-foreground": "0 0% 0%",
            "--heroui-warning": "37.03 91.27% 55.1%",
            "--heroui-code-background": "221.25 17.39% 18.04%",
            "--heroui-strong": "316.95 100% 65.29%",
            "--heroui-code-mdx": "316.95 100% 65.29%",
            "--heroui-divider-weight": "1px",
            "--heroui-disabled-opacity": ".5",
            "--heroui-font-size-tiny": "0.75rem",
            "--heroui-font-size-small": "0.875rem",
            "--heroui-font-size-medium": "1rem",
            "--heroui-font-size-large": "1.125rem",
            "--heroui-line-height-tiny": "1rem",
            "--heroui-line-height-small": "1.25rem",
            "--heroui-line-height-medium": "1.5rem",
            "--heroui-line-height-large": "1.75rem",
            "--heroui-radius-small": "8px",
            "--heroui-radius-medium": "12px",
            "--heroui-radius-large": "14px",
            "--heroui-border-width-small": "1px",
            "--heroui-border-width-medium": "2px",
            "--heroui-border-width-large": "3px",
            "--heroui-box-shadow-small": "0px 0px 5px 0px rgba(0, 0, 0, .02), 0px 2px 10px 0px rgba(0, 0, 0, .06), 0px 0px 1px 0px rgba(0, 0, 0, .3)",
            "--heroui-box-shadow-medium": "0px 0px 15px 0px rgba(0, 0, 0, .03), 0px 2px 30px 0px rgba(0, 0, 0, .08), 0px 0px 1px 0px rgba(0, 0, 0, .3)",
            "--heroui-box-shadow-large": "0px 0px 30px 0px rgba(0, 0, 0, .04), 0px 30px 60px 0px rgba(0, 0, 0, .12), 0px 0px 1px 0px rgba(0, 0, 0, .3)",
            "--heroui-hover-opacity": ".8"
        }
    },
    "defaultToken": false,
    "disableWebUI": false,
    "disableNonLANAccess": false
}
EOF
  echo "✅ 已生成配置文件: $CONFIG_FILE3"
else
  echo "⚠️ 已存在配置文件: $CONFIG_FILE3"
fi

# 预先计算变量，避免 heredoc 中复杂内嵌
UID_NUM=$(id -u)
GID_NUM=$(id -g)

# 使用真实厂商OUI前缀模拟全球唯一MAC地址
# 常见厂商OUI: Intel(00:1B:21), Dell(00:14:22), HP(00:1F:29), Cisco(00:1E:14), Apple(00:1F:F3)
OUI_LIST=("00:1B:21" "00:14:22" "00:1F:29" "00:1E:14" "00:1F:F3" "00:50:56" "08:00:27")
SELECTED_OUI=${OUI_LIST[$((RANDOM % ${#OUI_LIST[@]}))]}
MAC="${SELECTED_OUI}:$(printf "%02X" $((RANDOM % 256))):$(printf "%02X" $((RANDOM % 256))):$(printf "%02X" $((RANDOM % 256)))"
echo "🔍 选择 MAC 地址: $MAC"

# 随机选择设备名
HOSTNAME_LIST=("ubuntu" "root" "li" "wang" "gaoll" "chencc" "wangminw" "liyuepeng" "pingmeng" "danta" "luo" "liang" "yuwei")
SELECTED_HOSTNAME=${HOSTNAME_LIST[$((RANDOM % ${#HOSTNAME_LIST[@]}))]}
echo "🏷️ 选择设备名: $SELECTED_HOSTNAME"

COMPOSE_FILE="docker-compose.yml"

# 检查 docker-compose.yml 是否已存在，如果存在则不重新生成
if [ ! -f "./$QQ/$COMPOSE_FILE" ]; then
  echo "📝 生成 docker-compose.yml 配置文件..."
  # 使用临时 compose 文件启动该 QQ 的容器
  cat > "./$QQ/$COMPOSE_FILE" <<EOF
services:
  napcat_${QQ}:
    image: mlikiowa/napcat-docker:v4.8.106
    container_name: napcat_${QQ}
    hostname: ${SELECTED_HOSTNAME}
    restart: always
    network_mode: bridge
    mac_address: ${MAC}
    environment:
      - NAPCAT_UID=${UID_NUM}
      - NAPCAT_GID=${GID_NUM}
    ports:
      - "${WEBUI_PORT}:${WEBUI_PORT}"
      - "${HTTP_PORT}:${HTTP_PORT}"
    volumes:
      - ./napcat:/app/napcat/config
      - ./ntqq:/app/.config/QQ
      - ./cache:/app/napcat/cache
EOF
else
  echo "📋 使用已存在的 docker-compose.yml 配置文件"
fi

# 启动并检测结果
if docker compose -f "./$QQ/$COMPOSE_FILE" up -d; then
  echo "✅ 已启动 napcat_${QQ}"
  echo "主机名 ${SELECTED_HOSTNAME}"
  echo "MAC地址 ${MAC}"
  echo "端口映射 ${WEBUI_PORT}:${WEBUI_PORT}"
  echo "端口映射 ${HTTP_PORT}:${HTTP_PORT}"
  echo "📡 开始实时跟踪日志（Ctrl+C 退出日志跟踪，不影响容器运行）..."
  echo "----------------------------------------"
  
  # 等待容器完全启动
  sleep 2
  
  # 实时跟踪日志，使用trap捕获Ctrl+C信号
  trap 'echo -e "\n🔚 已退出日志跟踪，容器 napcat_${QQ} 继续在后台运行"; exit 0' INT
  docker logs --tail 50 -f "napcat_${QQ}"
else
  echo "❌ docker compose 启动失败，请查看: $COMPOSE_FILE"
  exit 1
fi
